from django import forms
from django.contrib import admin
from django.db.models.signals import pre_save
from django.dispatch import receiver

from .models import Product, Image, User, Coach
from django.utils.translation import gettext_lazy as _
from django.utils.html import format_html


# 产品管理界面
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = (
        'id','productname', 'subid', 'price', 'location', 'is_active', 'created_at',
        'total_use', 'maxtimes'
    )  # 添加 location

    list_filter = ('is_active', 'subid')  # 可过滤字段
    search_fields = ('productname', 'description')  # 可搜索字段
    ordering = ('-created_at',)  # 默认按创建时间倒序排序
    date_hierarchy = 'created_at'  # 可以按时间层级过滤

    fields = (
        'productname', 'subid', 'description', 'price', 'total_use', 'is_active',
        'created_at', 'covar_id', 'en_description', 'member_price', 'maxtimes', 'location'
    )  # 显示字段

    readonly_fields = ('created_at',)  # 只读字段


# 图片管理界面
@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
    list_display = ('id','name', 'url', 'type', 'created_at', 'format')  # 显示的字段
    list_filter = ('type',)  # 可过滤字段
    search_fields = ('name', 'description')  # 可搜索字段
    ordering = ('-created_at',)  # 默认按创建时间倒序排序

    fields = ('name', 'url', 'type', 'created_at', 'description', 'format')  # 需要显示的字段
    readonly_fields = ('created_at',)  # 只读字段


@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    # 显示在列表中的字段
    list_display = ('id', 'username', 'openid', 'phonenumber', 'created_at', 'membertime')

    # 可编辑字段
    list_editable = ('membertime',)

    # 为字段添加筛选器
    list_filter = ('created_at', 'avatar_id')  # 按照用户是否激活、创建时间和头像进行筛选

    # 为字段添加搜索功能
    search_fields = ('username', 'openid', 'phonenumber')  # 可以按用户名、微信 OpenID 和手机号进行搜索

    # 默认排序
    ordering = ('-created_at',)  # 按创建时间降序排序

    # 列表操作
    actions = ['reset_membertime', 'set_active', 'set_inactive']

    # 定义动作：重置会员时间
    def reset_membertime(self, request, queryset):
        # 批量操作，将所选用户的会员时间重置为 0
        queryset.update(membertime=0)
        self.message_user(request, _("Successfully reset the member time for selected users."), level='success')

    reset_membertime.short_description = _("Reset Member Time to 0")

    # 自定义排序
    def get_search_results(self, request, queryset, search_term):
        """增加自定义搜索逻辑"""
        queryset = super().get_search_results(request, queryset, search_term)
        # 自定义扩展搜索字段的行为
        return queryset
    reset_membertime.short_description = "重置会员时间为 0"
class CoachForm(forms.ModelForm):
    class Meta:
        model = Coach
        fields = '__all__'
        widgets = {
            'birth_date': forms.DateInput(attrs={'type': 'date'}),
            'description': forms.Textarea(attrs={'rows': 4}),
        }
@admin.register(Coach)
class CoachAdmin(admin.ModelAdmin):
    form = CoachForm

    list_display = ('id', 'name', 'phone_number', 'wechat_id', 'cover_image_preview', 'created_at')
    list_filter = ('created_at',)
    search_fields = ('name', 'phone_number', 'wechat_id')
    readonly_fields = ('created_at', 'updated_at', 'cover_image_preview')
    fieldsets = (
        (None, {
            'fields': ('name', 'birth_date')
        }),
        ('联系信息', {
            'fields': ('phone_number', 'wechat_id')
        }),
        ('描述信息', {
            'fields': ('description', 'en_description', 'tags')
        }),
        ('媒体信息', {
            'fields': ('cover_image', 'cover_image_preview')
        }),
        ('元数据', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def cover_image_preview(self, obj):
        if obj.cover_image:
            return format_html(
                '<img src="{}" style="max-height: 100px; max-width: 100px;" />',
                obj.cover_image.url
            )
        return "-"

    cover_image_preview.short_description = '封面预览'

    def save_model(self, request, obj, form, change):
        # 保存前的自定义逻辑
        if not obj.tags:
            obj.tags = "默认标签"
        super().save_model(request, obj, form, change)

@receiver(pre_save, sender=Coach)
def process_coach_tags(sender, instance, **kwargs):
    if instance.tags:
        # 清理标签格式：去空格、去重复、排序
        tags = [tag.strip().lower() for tag in instance.tags.split(',')]
        instance.tags = ','.join(sorted(set(tags)))